package flc.ast.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.stark.calculator.tax.constant.TaxConst;
import com.stark.calculator.tax.model.CityWage;
import com.stark.calculator.tax.model.DataProvider;
import com.stark.calculator.tax.model.DeductionBean;
import com.stark.calculator.tax.model.TaxCalBean;
import com.stark.calculator.tax.model.WageRateBean;
import com.stark.calculator.tax.viewmodel.DeductionViewModel;

import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.MySelectCityActivity;
import flc.ast.activity.TaxKind1RetActivity;
import flc.ast.adapter.MyDeductionAdapter;
import flc.ast.adapter.MyWageRateAdapter;
import flc.ast.databinding.FragmentTaxKind1Binding;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.utils.Str2NumUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TaxKind1Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TaxKind1Fragment extends BaseNoModelFragment<FragmentTaxKind1Binding> {

    private static final int REQ_SEL_CITY = 1;
    private CityWage mSelCityWage;
    private boolean isAll = true;
    private MyWageRateAdapter mWageRateAdapter;
    private MyDeductionAdapter mDeductionAdapter;
    private List<DeductionBean> mDeductionBeanList;
    private String yangPerson, yangCompany, ylPerson, ylCompany, shiYPerson, shiYCompany, gsPerson, gsCompany, syPerson, syCompany, gjjPerson, gjjCompany;
    private Dialog myPaymentDialog, myDeductionDialog;
    private static final String[] sThresholdValues = new String[]{"5000", "6800"};


    @Override
    protected int onCreate() {
        return R.layout.fragment_tax_kind1;
    }

    @Override
    protected void initView() {
        //缴纳城市
        CityWage selCityWage = DataProvider.getSelCityWage();
        mSelCityWage = selCityWage;
        mDataBinding.tvTaxKind1City.setText(selCityWage.cityName);
        //个税起征点
        mDataBinding.tvTaxKind1Qzd.setText(sThresholdValues[0]);
        //专项附加扣除
        mDeductionBeanList = DataProvider.getDeductions();
        updateDeduction();

        mDataBinding.tvTaxKind1Qbjn.setOnClickListener(this);
        mDataBinding.tvTaxKind1Bfjn.setOnClickListener(this);
        mDataBinding.llTaxKind1City.setOnClickListener(this);
        mDataBinding.llTaxKind1Qzd.setOnClickListener(this);
        mDataBinding.llTaxKind1Xiang.setOnClickListener(this);
        mDataBinding.llTaxKind1Xm.setOnClickListener(this);
        mDataBinding.tvCalculate.setOnClickListener(this);
        //缴纳项目弹框
        paymentDialog();
        //专项扣除弹框
        deductionDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvTaxKind1Qbjn://全部缴纳
                clearSelection();
                isAll = true;
                mDataBinding.llTaxKind1Bfjn.setVisibility(View.GONE);
                mDataBinding.tvTaxKind1Qbjn.setTextColor(Color.WHITE);
                mDataBinding.tvTaxKind1Qbjn.setBackgroundResource(R.drawable.shape_rate_type);
                break;
            case R.id.tvTaxKind1Bfjn://部分缴纳
                clearSelection();
                isAll = false;
                mDataBinding.llTaxKind1Bfjn.setVisibility(View.VISIBLE);
                mDataBinding.tvTaxKind1Bfjn.setTextColor(Color.WHITE);
                mDataBinding.tvTaxKind1Bfjn.setBackgroundResource(R.drawable.shape_rate_type);
                break;
            case R.id.llTaxKind1City://缴纳城市
                selCity();
                break;
            case R.id.llTaxKind1Qzd://个税起征点
                showThresholdDialog();
                break;
            case R.id.llTaxKind1Xiang://专项扣除
                myDeductionDialog.show();
                break;
            //缴纳项目弹框
            case R.id.ivDialogDeductionCancel:
                myDeductionDialog.dismiss();
                mDeductionAdapter.setList(DataProvider.getDeductions());
                break;
            case R.id.tvDialogDeductionConfirm:
                myDeductionDialog.dismiss();
                mDeductionBeanList = mDeductionAdapter.getData();
                DataProvider.saveDeductions(mDeductionBeanList);
                updateDeduction();
                break;
            case R.id.llTaxKind1Xm://缴纳项目
                myPaymentDialog.show();
                break;
            //缴纳项目弹框
            case R.id.ivDialogPaymentCancel:
                paymentCancel();
                mWageRateAdapter.notifyDataSetChanged();
                myPaymentDialog.dismiss();
                break;
            case R.id.tvDialogPaymentConfirm:
                paymentConfirm();
                myPaymentDialog.dismiss();
                break;
            case R.id.tvCalculate://计算
                calculate();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        mDeductionAdapter.getItem(position).setChecked(!mDeductionAdapter.getItem(position).isChecked());
        mDeductionAdapter.notifyItemChanged(position);
    }

    @Override
    protected void initData() {

    }

    private void selCity() {
        Intent intent = new Intent(getActivity(), MySelectCityActivity.class);
        startActivityForResult(intent, REQ_SEL_CITY);
    }

    private void calculate() {
        TaxCalBean calModel = new TaxCalBean();
        //税前工资
        String text = mDataBinding.etTaxKin1Sqgz.getText().toString();
        if (TextUtils.isEmpty(text)) {
            mDataBinding.etTaxKin1Sqgz.requestFocus();
            ToastUtils.showShort(R.string.input_pre_tax_salary);
            return;
        }
        float salary = 0;
        try {
            salary = Float.parseFloat(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (salary == 0) {
            mDataBinding.etTaxKin1Sqgz.requestFocus();
            ToastUtils.showShort(R.string.input_pre_tax_salary);
            return;
        }
        calModel.preTaxSalary = salary;

        //实缴基数
        if (isAll) {
            /**
             * 全额缴纳：当前工资小于最低社保基数时，社保缴纳基数设为最低社保基数，
             * 当前工资大于最高社保基数时，社保缴纳基数设为最高社保基数，否则为税前工资本身
             */
            float minSheBao = Str2NumUtil.parse(mSelCityWage.rate.shebaoMin);
            float maxSheBao = Str2NumUtil.parse(mSelCityWage.rate.shebaoMax);
            if (salary < minSheBao) {
                calModel.sheBaoBase = minSheBao;
            } else if (salary > maxSheBao) {
                calModel.sheBaoBase = maxSheBao;
            } else {
                calModel.sheBaoBase = salary;
            }
            /**
             * 全额缴纳：当前工资小于最低公积金基数时，公积金缴纳基数设为最低公积金基数，
             * 当前工资大于最高公积金基数时，公积金缴纳基数设为最高公积金基数，否则为税前工资本身
             */
            float minGjj = Str2NumUtil.parse(mSelCityWage.rate.gongJiJinMin);
            float maxGjj = Str2NumUtil.parse(mSelCityWage.rate.gongJiJinMax);
            if (salary < minGjj) {
                calModel.gjjBase = minGjj;
            } else if (salary > maxGjj) {
                calModel.gjjBase = maxGjj;
            } else {
                calModel.gjjBase = salary;
            }

        } else {
            //部分缴纳
            //社保
            text = mDataBinding.etTaxKin1Sjsb.getText().toString();
            if (TextUtils.isEmpty(text)) {
                mDataBinding.etTaxKin1Sjsb.requestFocus();
                ToastUtils.showShort(R.string.input_valid_amount_tip);
                return;
            }
            calModel.sheBaoBase = Str2NumUtil.parse(text);
            //公积金
            text = mDataBinding.etTaxKin1Sjgjj.getText().toString();
            if (TextUtils.isEmpty(text)) {
                mDataBinding.etTaxKin1Sjgjj.requestFocus();
                ToastUtils.showShort(R.string.input_valid_amount_tip);
                return;
            }
            calModel.gjjBase = Str2NumUtil.parse(text);
        }

        //个税起征点
        text = mDataBinding.tvTaxKind1Qzd.getText().toString();
        calModel.threshold = Str2NumUtil.parse(text);

        //附加扣除
        calModel.deduction = getDeduction();

        //社保、公积金比例
        List<WageRateBean> rateBeanList = mWageRateAdapter.getDatas();
        setTaxCalModelRate(calModel, rateBeanList);

        //TaxCalRetActivity.start(getContext(), calModel);
        goCalRetActivity(calModel);
    }

    protected void goCalRetActivity(TaxCalBean calBean) {
        TaxKind1RetActivity.start(getContext(), calBean);
    }

    /**
     * 设置个税计算实例中的五险一金的各比例数据
     *
     * @param model
     * @param rateBeanList
     */
    private void setTaxCalModelRate(TaxCalBean model, List<WageRateBean> rateBeanList) {
        if (model == null || rateBeanList == null) {
            return;
        }
        for (WageRateBean rateBean : rateBeanList) {
            switch (rateBean.getType()) {
                case YANG_LAO:
                    model.yangLaoPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.yangLaoCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case YI_LIAO:
                    model.yiLiaoPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.yiLiaoCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case SHI_YE:
                    model.shiYePersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.shiYeCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case GONG_SHANG:
                    model.gongShangPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.gongShangCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case SHENG_YU:
                    model.shengYuPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.shengYuCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case GONG_JI_JIN:
                    model.gjjPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.gjjCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
            }
        }
    }

    private void paymentCancel() {
        mWageRateAdapter.getDatas().get(1).setPersonal(yangPerson);
        mWageRateAdapter.getDatas().get(1).setCompany(yangCompany);
        mWageRateAdapter.getDatas().get(2).setPersonal(ylPerson);
        mWageRateAdapter.getDatas().get(2).setCompany(ylCompany);
        mWageRateAdapter.getDatas().get(3).setPersonal(shiYPerson);
        mWageRateAdapter.getDatas().get(3).setCompany(shiYCompany);
        mWageRateAdapter.getDatas().get(4).setPersonal(gsPerson);
        mWageRateAdapter.getDatas().get(4).setCompany(gsCompany);
        mWageRateAdapter.getDatas().get(5).setPersonal(syPerson);
        mWageRateAdapter.getDatas().get(5).setCompany(syCompany);
        mWageRateAdapter.getDatas().get(6).setPersonal(gjjPerson);
        mWageRateAdapter.getDatas().get(6).setCompany(gjjCompany);
    }


    private void paymentConfirm() {
        yangPerson = mWageRateAdapter.getDatas().get(1).getPersonal();
        yangCompany = mWageRateAdapter.getDatas().get(1).getCompany();
        ylPerson = mWageRateAdapter.getDatas().get(2).getPersonal();
        ylCompany = mWageRateAdapter.getDatas().get(2).getCompany();
        shiYPerson = mWageRateAdapter.getDatas().get(3).getPersonal();
        shiYCompany = mWageRateAdapter.getDatas().get(3).getCompany();
        gsPerson = mWageRateAdapter.getDatas().get(4).getPersonal();
        gsCompany = mWageRateAdapter.getDatas().get(4).getCompany();
        syPerson = mWageRateAdapter.getDatas().get(5).getPersonal();
        syCompany = mWageRateAdapter.getDatas().get(5).getCompany();
        gjjPerson = mWageRateAdapter.getDatas().get(6).getPersonal();
        gjjCompany = mWageRateAdapter.getDatas().get(6).getCompany();
    }

    //缴纳项目弹框
    private void paymentDialog() {
        myPaymentDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_payment, null);
        myPaymentDialog.setContentView(inflate);
        myPaymentDialog.setCancelable(false);
        Window dialogWindow = myPaymentDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogPaymentCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogPaymentConfirm);
        RecyclerView rvPaymentItems = inflate.findViewById(R.id.rv_payment_items);

        //缴纳项目
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        rvPaymentItems.setLayoutManager(layoutManager);
        MyWageRateAdapter adapter = new MyWageRateAdapter(true);
        mWageRateAdapter = adapter;
        adapter.setDatas(DataProvider.getWageRateItems(DataProvider.getSelCityWage()));
        rvPaymentItems.setAdapter(adapter);

        paymentConfirm();

        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    //专项扣除弹框
    private void deductionDialog() {
        myDeductionDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_deduction, null);
        myDeductionDialog.setContentView(inflate);
        myDeductionDialog.setCancelable(false);
        Window dialogWindow = myDeductionDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogDeductionCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogDeductionConfirm);
        RecyclerView rvDeductionItems = inflate.findViewById(R.id.rv_deduction_items);

        //缴纳项目
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        rvDeductionItems.setLayoutManager(layoutManager);
        mDeductionAdapter = new MyDeductionAdapter();
        DeductionViewModel mViewModel = new DeductionViewModel();
        mViewModel.getDeductionList().observe(this, new Observer<List<DeductionBean>>() {
            @Override
            public void onChanged(List<DeductionBean> deductionBeans) {
                mDeductionAdapter.setNewInstance(deductionBeans);
            }
        });
        rvDeductionItems.setAdapter(mDeductionAdapter);

        mViewModel.loadDeductions(mContext);

        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
        mDeductionAdapter.setOnItemClickListener(this);
    }

    private void showThresholdDialog() {
        final String[] items = getResources().getStringArray(R.array.Threshold);
        new XPopup.Builder(getContext())
                .asCenterList(getString(R.string.please_select), items,
                        null,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                mDataBinding.tvTaxKind1Qzd.setText(sThresholdValues[position]);

                            }
                        })
                .show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQ_SEL_CITY) {
                if (data == null) return;
                CityWage cityWage = (CityWage) data.getSerializableExtra(TaxConst.KEY_WAGE);
                DataProvider.saveSelCityWage(cityWage);
                mSelCityWage = cityWage;
                //通知相关UI更新
                mDataBinding.tvTaxKind1City.setText(mSelCityWage.cityName);
                if (mWageRateAdapter != null) {
                    mWageRateAdapter.setDatas(DataProvider.getWageRateItems(mSelCityWage));
                    paymentConfirm();
                }
            }
        }
    }

    private void updateDeduction() {
        int count = 0;
        int amount = 0;
        if (mDeductionBeanList != null) {
            for (DeductionBean bean : mDeductionBeanList) {
                if (bean.isChecked()) {
                    try {
                        amount += Integer.parseInt(bean.getValue());
                        count++;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        String text = getString(R.string.deduction_amount_format, count, amount);
        mDataBinding.tvTaxKind1Xiang.setText(text);
    }

    private void clearSelection() {
        mDataBinding.tvTaxKind1Qbjn.setTextColor(Color.parseColor("#000000"));
        mDataBinding.tvTaxKind1Qbjn.setBackground(null);
        mDataBinding.tvTaxKind1Bfjn.setTextColor(Color.parseColor("#000000"));
        mDataBinding.tvTaxKind1Bfjn.setBackground(null);
    }


    /**
     * 获取专项附加扣除金额
     *
     * @return
     */
    private float getDeduction() {
        float value = 0;
        if (mDeductionBeanList == null) {
            return value;
        }
        for (DeductionBean bean : mDeductionBeanList) {
            if (bean.isChecked()) {
                value += Str2NumUtil.parse(bean.getValue());
            }
        }
        return value;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //退出该界面时，要保存下附加扣除数据
        DataProvider.saveDeductions(mDeductionBeanList);
    }
}